package com.wnhz.work.yz.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.Selection;
import android.text.Spannable;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.wnhz.work.yz.BaseActivity;
import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.bean.Finish1;
import com.wnhz.work.yz.bean.Install2Bean;
import com.wnhz.work.yz.listener.OnItemClickListener;
import com.yanzhenjie.recyclerview.swipe.Closeable;
import com.yanzhenjie.recyclerview.swipe.OnSwipeMenuItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenu;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuAdapter;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItem;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.DecimalFormat;
import java.util.ArrayList;

public class LookDetails1Activity extends BaseActivity implements View.OnClickListener {
    private SwipeMenuRecyclerView recycler;
    private ArrayList<Install2Bean.InfoEntity.ListEntity> list = new ArrayList<>();

    private TextView price, nums;
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(Finish1 event) {
        finish();
    }


    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);//反注册EventBus
        super.onDestroy();
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_look_details1);
        EventBus.getDefault().register(this);
      //  MyApplication.getInstance().addDestoryActivity(this, "look2");
        initTitle();
        initView();
        setPrice();
    }

    private void setPrice() {
        String num2 = "共计：<color=\"#ff0000\">" + list.size() + "</color>个服务项目";
        nums.setText(Html.fromHtml(num2));
        Double total = 0d;
        for (int n = 0; n < list.size(); n++) {
            total += Double.parseDouble(list.get(n).getPrice()) * Double.parseDouble(list.get(n).getNum());
        }
        DecimalFormat df = new DecimalFormat("######0.00");
        price.setText("￥" + df.format(total));
    }


    private void initView() {
        price = (TextView) findViewById(R.id.price);
        nums = (TextView) findViewById(R.id.nums);
        list = (ArrayList<Install2Bean.InfoEntity.ListEntity>) getIntent().getSerializableExtra("list");

        recycler = (SwipeMenuRecyclerView) findViewById(R.id.recycler);

        initRecycler(recycler);


    }

    private Look min;

    public void initRecycler(SwipeMenuRecyclerView recycler_view) {
        recycler_view.setLayoutManager(new LinearLayoutManager(LookDetails1Activity.this));
        recycler_view.setHasFixedSize(true);
        recycler_view.setItemAnimator(new DefaultItemAnimator());
        recycler_view.setSwipeMenuCreator(swipeMenuCreator);
        recycler_view.setSwipeMenuItemClickListener(menuItemClickListener);


        //
        min = new Look(list, this);
        min.setOnItemClickListener(onItemClickListener);

        recycler_view.setAdapter(min);
    }

    private OnItemClickListener onItemClickListener = new OnItemClickListener() {
        @Override
        public void onItemClick(int position) {
            //   Toast.makeText(FamilyEditActivity.this, "我是第" + position + "条。", Toast.LENGTH_SHORT).show();
        }
    };
    /**
     * 菜单创建器。
     */
    private SwipeMenuCreator swipeMenuCreator = new SwipeMenuCreator() {
        @Override
        public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int viewType) {
            int size = getResources().getDimensionPixelSize(R.dimen.item_height);
            SwipeMenuItem deleteItem = new SwipeMenuItem(LookDetails1Activity.this)
                    .setText("删除")
                    .setWidth(size)
                    .setTextColor(getResources().getColor(R.color.white))
                    .setBackgroundColor(getResources().getColor(R.color.red))
                    .setHeight(dip2px(LookDetails1Activity.this, 110));

            //      swipeLeftMenu.addMenuItem(deleteItem);
            swipeRightMenu.addMenuItem(deleteItem);

        }
    };


    public int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 菜单点击监听。
     */
    private OnSwipeMenuItemClickListener menuItemClickListener = new OnSwipeMenuItemClickListener() {
        @Override
        public void onItemClick(Closeable closeable, int adapterPosition, int menuPosition, int direction) {
            closeable.smoothCloseMenu();// 关闭被点击的菜单。

            if (direction == SwipeMenuRecyclerView.RIGHT_DIRECTION) {
                list.remove(adapterPosition);
                min.notifyDataSetChanged();
                setPrice();
            }
        }
    };


    private void initTitle() {
        TextView title = (TextView) findViewById(R.id.view_main_middle_title);
        title.setText("查看清单");
        findViewById(R.id.btn_main_left).setOnClickListener(this);
        TextView submit = (TextView) findViewById(R.id.submit);
        submit.setText("下一步");
        submit.setVisibility(View.VISIBLE);
        submit.setOnClickListener(this);
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = getIntent();
            intent.putExtra("list", list);
            setResult(RESULT_OK, intent);
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_main_left:
                Intent intent = getIntent();
                intent.putExtra("list", list);
                setResult(RESULT_OK, intent);
                finish();
                break;
            case R.id.submit:
                if (MyApplication.getInstance().getUserBean() == null) {
                    MyToast("请登录");
                    startActivity(new Intent(getApplicationContext(), LoginFirstActivity.class));
                    return;
                }
                if (list == null) {
                    return;
                }
                ArrayList<Install2Bean.InfoEntity.ListEntity> list2 = new ArrayList<>();
                for (int i = 0; i < list.size(); i++) {
                    if (Integer.parseInt(list.get(i).getNum()) > 0) {
                        list2.add(list.get(i));
                    }
                }
                if (list2.size() == 0) {
                    MyToast("请至少选择一个");
                    return;
                }

                startActivity(new Intent(this, Details1ToPayActivity.class).putExtra("list", list2).putExtra("pid", getIntent().getStringExtra("pid")).putExtra("type", getIntent().getStringExtra("type")));
                break;
        }
    }

    class Look extends SwipeMenuAdapter<Look.DefaultViewHolder> {


        private OnItemClickListener mOnItemClickListener;
        private Context context;
        ArrayList<Install2Bean.InfoEntity.ListEntity> list = new ArrayList<>();

        public Look(ArrayList<Install2Bean.InfoEntity.ListEntity> list, Context context) {
            this.context = context;
            this.list = list;
        }

        public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
            this.mOnItemClickListener = onItemClickListener;
        }


        @Override
        public void onBindViewHolder(Look.DefaultViewHolder holder, int position) {
            holder.setData(list.get(position));
            holder.setOnItemClickListener(mOnItemClickListener);
        }

        @Override
        public int getItemCount() {
            return list == null ? 0 : list.size();
        }

        @Override
        public View onCreateContentView(ViewGroup parent, int viewType) {
            return LayoutInflater.from(parent.getContext()).inflate(R.layout.item_install_detail1, parent, false);
        }

        @Override
        public Look.DefaultViewHolder onCompatCreateViewHolder(View realContentView, int viewType) {
            return new DefaultViewHolder(realContentView);
        }


        class DefaultViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
            ImageView img, reduce, ll_add;

            TextView shopping_number, text_title, text_desc, text_price;
            OnItemClickListener mOnItemClickListener;

            public DefaultViewHolder(View itemView) {
                super(itemView);
                itemView.setOnClickListener(this);
                img = (ImageView) itemView.findViewById(R.id.img);
                shopping_number = (TextView) itemView.findViewById(R.id.shopping_number);
                text_title = (TextView) itemView.findViewById(R.id.text_title);
                text_desc = (TextView) itemView.findViewById(R.id.text_desc);
                text_price = (TextView) itemView.findViewById(R.id.text_price);
                reduce = (ImageView) itemView.findViewById(R.id.reduce);
                ll_add = (ImageView) itemView.findViewById(R.id.ll_add);

            }

            public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
                this.mOnItemClickListener = onItemClickListener;
            }


            @Override
            public void onClick(View v) {
                if (mOnItemClickListener != null) {
                    mOnItemClickListener.onItemClick(getAdapterPosition());
                }
            }


            public void setData(final Install2Bean.InfoEntity.ListEntity data) {

                ImageLoader.getInstance().displayImage(data.getGoods_img(), img);
                shopping_number.setText(data.getNum());

                text_title.setText(data.getGoods_name());
                text_desc.setText(data.getGoods_des());
                text_price.setText(data.getPrice());
                reduce.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if ("".equals(shopping_number.getText().toString()) || Integer.parseInt(shopping_number.getText().toString()) <= 0) {
                            MyToast("不能再减了");
                            data.setNum("0");
                            return;
                        } else {
                            shopping_number.setText(Integer.parseInt(data.getNum()) - 1 + "");
                            data.setNum(shopping_number.getText().toString());
                            setPrice();
                        }
                    }
                });


                ll_add.setOnClickListener(
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if ("".equals(shopping_number.getText().toString())) {
                                    shopping_number.setText("1");
                                    data.setNum("1");
                                } else {
                                    shopping_number.setText(Integer.parseInt(data.getNum()) + 1 + "");

                                    data.setNum(shopping_number.getText().toString());
                                    setPrice();
                                }

                            }
                        }
                );
                shopping_number.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        final AlertDialog.Builder builder = new AlertDialog.Builder(LookDetails1Activity.this);
                        View view = View.inflate(LookDetails1Activity.this, R.layout.dialog_edit, null);
                        TextView queding1 = (TextView) view.findViewById(R.id.queding1);
                        TextView quxaio1 = (TextView) view.findViewById(R.id.quxiao1);
                        final EditText shopping_number2 = (EditText) view.findViewById(R.id.shopping_number);
                        shopping_number2.setText("" + Double.parseDouble(data.getNum()));

                        shopping_number.postInvalidate();
                        //切换后将EditText光标置于末尾
                        CharSequence charSequence = shopping_number.getText();
                        if (charSequence instanceof Spannable) {
                            Spannable spanText = (Spannable) charSequence;
                            Selection.setSelection(spanText, charSequence.length());
                        }

                        builder.setView(view);
                        final AlertDialog show = builder.show();
                        Window dialogWindow = show.getWindow();
                        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
                        dialogWindow.setGravity(Gravity.CENTER);
                        dialogWindow.setAttributes(lp);
                        queding1.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                int nums = Integer.parseInt(data.getNum());
                                try {
                                    nums = Integer.parseInt(shopping_number2.getText().toString());
                                } catch (Exception e) {
                                    nums = Integer.parseInt(data.getNum());
                                }
                                shopping_number.setText(nums + "");
                                data.setNum(shopping_number.getText().toString());
                                setPrice();
                                show.dismiss();
                            }
                        });
                        quxaio1.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                show.dismiss();
                            }
                        });

                    }
                });


            }
        }


    }

}
